<?

class render_html
{
	public static function action( action_controller $action )
	{
		if ( config::get('html_meta') ) foreach ( config::get('html_meta') as $key => $value )
		{
			if ( !helper_html::$meta[$key] ) helper_html::$meta[$key] = $value;
		}

		if ( config::get('recompile') )
		{
			$task = new compile_static_task();
			$task->execute();
		}

		response::set_header('Content-Type', 'text/html; charset=utf-8');

		$view_path = $action->get_layout() ?
					self::get_layout_path($action->get_layout()) :
					self::get_view_path($action->get_view());

		return self::render_template($view_path);
	}

	public static function render_template( $path, $context = array() )
	{
		if ( $action = context::get_action() )
			foreach ( $action as $key => $value ) $$key = $value;

		foreach ( $context as $key => $value ) $$key = $value;

		ob_start();
		include $path;
		return ob_get_clean();
	}

	public static function render_slot( $slot, $context = array() )
	{
		$path = context::get_action()->get_view();

		do
		{
			$path = dirname($path);
			if ( $path == '.' ) $path = '';

			if ( $path )
			{
				$path = $path . '/';
				$slot_path = self::get_view_path( $path . 'slot.' . $slot);
			}
			else
			{
				$slot_path = self::get_view_path( 'slot.' . $slot);
			}

			if ( $slot_exists = is_file($slot_path) ) break;
			
		} while( $path );

		if ( !$slot_exists ) $slot_path = self::get_layout_path('slots/' . $slot);

		return is_file($slot_path) ? self::render_template($slot_path, $context) : null;
	}

	public static function render_partial( $view, $context = array() )
	{
		$path = self::get_view_path($view);
		$path = dirname($path) . '/partials/' . basename($view) . '.php';
		return self::render_template($path, $context);
	}

	public static function render_view( $view, $context = array() )
	{
		if ( config::all()->ssi['enable'] )
		{
			return '<!--# include virtual="/ssi' . $_SERVER['REQUEST_URI'] . '" -->';
		}
		else
		{
			return self::render_template(self::get_view_path($view), $context);
		}
	}

	public static function get_view_path( $view )
	{
		$view = explode('/', $view);
		$name = array_pop($view);
		$view = implode('/', $view) . '/_view/' . $name;

		return PROJECT_PATH . '/apps/' . front_controller::get_application() . '/actions/' .
				$view . '.view.php';
	}

	public static function get_layout_path( $layout )
	{
		return PROJECT_PATH . '/apps/' . front_controller::get_application() . '/layout/' .
				$layout . '.view.php';
	}

	public static function cached( $key, $file, $ttl = 0 )
	{
		if ( $html = cache::get($key) ) return $html;

		ob_start();
		include $file;
		$html = ob_get_clean();

		if ( !config::get('debug') ) cache::set($key, $html, $ttl);
		return $html;
	}
}